import {
  ApiGetSet,
  getEnterRoom,
  sendMessage
} from '../../api/index'
const app = getApp()
let typingInterval = null
Page({
  data: {
    deepArr: [{
      lable: '图文问诊',
      value: '/pages/graphicConsultation/index?text=图文问诊'
    },{
      lable: '缴费记录',
      value: '/pages/paymentRecords/index?text=缴费记录'
    },{
      lable: '团队问诊',
      value: '/pages/teamConsultation/index?text=团队问诊'
    },
  ],
    focus: false,
    offsetTop: 0,
    scrollTop: 0,
    inputValue: "", // 输入框内容
    chatList: [
      // 初始化对话数据，可从接口获取后动态渲染
      {
        type: "system",
        content: "那头痛是从什么时候开始的呢？最近有没有加重的趋势？如果以下没有符合您的情况，您也可以直接打字或点击麦克风语音输入，告诉我您现在的症状或问题",
        options: [
          "一周前开始，逐渐加重",
          "一周前开始，没有加重",
          "其他",
        ],
      },
      {
        type: "user",
        content: "三天前"
      },
      {
        type: "system",
        content: "我明白了。除了头痛，您还有其他症状吗？比如发热、恶心、呕吐等？如果以下没有符合您的情况，您也可以直接打字或点击麦克风语音输入，告诉我您现在的症状或问题",
        options: ["有发热", "有恶心", "有呕吐", "没有这些症状"],
      },
      {
        type: "user",
        content: "有呕吐，早晚各吐一次"
      },
      {
        type: "system",
        content: "正在思考中···"
      },
    ],
  },

  onLoad() {
    this.getRoomId()
  },
  onShow() {
    this.getSet()
  },
  getSet(){
    ApiGetSet().then(res => {
      this.setData({
        getSet: res.data
      })
    })
  },
  handleTap(e) {
    console.log(e._relatedInfo.anchorTargetText)
  },
  getOrder(e) {
    let text = e.currentTarget.dataset.v
    console.log(text)
    if (text == '问诊列表') {
      wx.navigateTo({
        url: '/pages/consultationRecord/index',
      })
    }
    if (text == '处方列表') {
      wx.navigateTo({
        url: '/pages/doctorAdvice/index',
      })
    }
    if (text == '缴费订单') {
      wx.navigateTo({
        url: '/pages/paymentRecords/index',
      })
    }
    if (text == '立即问诊') {
      wx.navigateBack()
    }
  },
  /*   onWindowResize() {
      // 窗口大小变化时重新计算高度
      this.calculateScrollHeight();
    }, */
  onHeightchange(e) {
    this.setData({
      offsetTop: e.detail.height
    })
    this.scrollToBottom()
  },





  getRoomId() {
    getEnterRoom().then(res => {
      res.data.message.forEach(item => {
        if (item.role == 'assistant') {
          item.content = this.getData(item.content)
        }
      })
      this.setData({
        room_id: res.data.room_id,
        messageArr: res.data.message.reverse(),
      })
      this.scrollToBottom();
    })
  },
  //解析文件
  getData(val) {
    return app.towxml(val, 'markdown', {
      base: 'https://www.huhailong.vip',
      theme: 'dark',
      events: {
        tap: (e) => {
            let text = e._relatedInfo.anchorTargetText.replace('请点击进入','')
            console.log(text)
         let data =  this.data.deepArr.find(item=>{
            if(item.lable==text){
              return item
            }
          })
          if (data) {
            wx.navigateTo({
              url: data.value,
            })
          } 

        }
      }
    });
  },



  // 切换用户
  /* switchUser() {
    wx.showToast({
      title: "切换用户逻辑待实现",
      icon: "none"
    });
  }, */

  // 处理选项点击
  /*  handleOption(e) {
     const content = e.currentTarget.dataset.content;
     // 模拟添加用户回复到聊天列表
     this.setData({
       chatList: [
         ...this.data.chatList,
         {
           type: "user",
           content: content
         },
       ],
     });
     // 可在此调用接口，将用户选择内容发送给后端，获取系统回复后再添加到 chatList
     wx.showLoading({
       title: "获取回复中"
     });
     setTimeout(() => {
       wx.hideLoading();
       // 模拟系统回复（实际替换为接口返回数据）
       this.setData({
         chatList: [
           ...this.data.chatList,
           {
             type: "system",
             content: "收到您的反馈，继续为您分析···",
             options: [], // 可根据实际情况设置新选项
           },
         ],
       });
     }, 1500);
   }, */

  // 退出对话
  /*   exitChat() {
      wx.navigateBack();
    },
   */
  // 输入框内容变化
  onInput(e) {
    this.setData({
      inputValue: e.detail.value,
      focus: true
    });
  },



  // 发送消息

  sendMsg() {
    clearInterval(typingInterval);
    let that = this
    if (!this.data.inputValue.trim()) return;
    let obj = [{
      content: this.data.inputValue,
      id: this.data.messageArr.length,
      role: "user",
      room_id: this.data.room_id,
    }, {
      content: this.getData("正在加载中....."),
      id: this.data.messageArr.length + 1,
      role: "assistant",
      room_id: this.data.room_id,
    }]
    this.data.messageArr = this.data.messageArr.concat(obj)
    let content = this.data.inputValue
    this.setData({
      messageArr: this.data.messageArr,
      inputValue: "",
    })
    this.scrollToBottom();
    console.log(content)
    //判断是否存在快捷用
   let data =  this.data.deepArr.find(item=>{
      if(item.lable==content){
        return item
      }
    })
    if (data) {
      let length = this.data.messageArr.length - 1
      this.setData({
        [`messageArr[${length}].content`]: this.getData(`请点击进入${data.lable}`)
      })
    } else {
      // 模拟系统回复
      sendMessage({
        room_id: this.data.room_id,
        content
      }).then(res => {
        that.typewriterEffect(res)
        this.scrollToBottom();
      }).finally(_ => {
        this.setData({
          inputValue: ""
        })
      })
    }
  },

  typewriterEffect(text) {
    let currentIndex = 0;
    typingInterval = setInterval(() => {
      const partialText = text.slice(0, currentIndex + 1);
      let length = this.data.messageArr.length - 1
      this.setData({
        [`messageArr[${length}].content`]: this.getData(partialText)
      })
      currentIndex++;
      this.scrollToBottom()
      // 判断是否已经显示完所有文字
      if (currentIndex === text.length) {
        clearInterval(typingInterval); // 清除定时器
      }
    }, 100);
  },

  scrollToBottom() {
    const query = wx.createSelectorQuery().in(this);
    query.select('#chatList').boundingClientRect(rect => {
      // 直接滚动到列表最底部
      this.setData({
        scrollTop: 99999999
      });
    }).exec();
  }
  /*   wx.pageScrollTo({
      selector: '#input-bar',
      offsetTop: 0, //偏移的位置
      duration: 0,
    }); */

});